在第二十天,你成功地將 MVVM 架構應用在一個實際的程式解題上,這證明你已經具備了專業級的程式設計思維。
但隨著 App 功能的增加,我們可能會遇到一個問題:如何在同一個畫面上,顯示多個獨立的 UI 模組?
想像一個新聞 App:左邊是一個新聞列表,右邊是新聞的詳細內容。當螢幕很小時,我們只顯示列表,點擊後跳到新頁面顯示內容。但如果螢幕夠大(例如平板),我們希望同時顯示這兩個部分。
這時,我們就需要今天的重點:Fragment。
Fragment?Fragment 就像是 App 的 「子畫面」 或 「樂高模組」。
Activity (大畫面) 就像是一座樂高積木的底板。Fragment (樂高模組)。Fragment 都有自己的生命週期和 UI 畫面,可以獨立運作。Fragment 讓你的 UI 可以被切割成可重複使用的模組。Fragment,或將多個 Fragment 放在同一個畫面上。Fragment 的基本結構一個 Fragment 就像一個簡化版的 Activity,它也有自己的生命週期。
Fragment 需要寄居在 Activity 上:Fragment 本身無法獨立存在,它必須依附在一個 Activity 容器中。Fragment 有自己的 XML 佈局檔案:就像 Activity 有 activity_main.xml 一樣,Fragment 也有自己的 fragment_*.xml。Fragment 有自己的 Java 程式碼檔案:用來處理自己的 UI 和邏輯,例如 MyFragment.java。今天,我們將會建立一個最簡單的 Fragment,並將它顯示在 MainActivity 上。
Fragment 類別在 Android Studio 中,找到 MainActivity.java 所在的資料夾,右鍵點擊,選擇 New -> Fragment -> Fragment (Blank)。
Fragment 取名為 HelloFragment。Android Studio 會自動為你建立 HelloFragment.java 和 fragment_hello.xml 這兩個檔案。fragment_hello.xml打開新建立的 fragment_hello.xml,我們只需要放入一個 TextView。
`<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HelloFragment"
android:background="#DDDDDD">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="這是一個 Fragment!"
android:textSize="24sp" />
</FrameLayout>`
MainActivity.java現在,我們需要告訴 MainActivity,請它把 HelloFragment 載入到畫面上。
`import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 假設你用的是 activity_main.xml
// 1. 取得 Fragment 管理器
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// 2. 建立 Fragment 實例
HelloFragment helloFragment = new HelloFragment();
// 3. 將 Fragment 加入到指定的 View 容器中
// 這裡的 R.id.fragment_container 是你需要在 activity_main.xml 中建立的 FrameLayout
transaction.add(R.id.fragment_container, helloFragment);
// 4. 提交交易
transaction.commit();
}
}`
activity_main.xml在 MainActivity 的 XML 檔案中,新增一個容器,用來裝載 Fragment。FrameLayout 是最常用的容器。
`<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />`
MainActivity 的畫面被你新建立的 Fragment 所取代。今天我們學會了 Fragment 的基本概念,以及它在 App 模組化設計中的重要性。我們也成功地完成了:
Fragment 類別和它的佈局檔案。MainActivity 中使用 FragmentTransaction,將 Fragment 載入到畫面上。明天,我們會學習更進階的 Fragment 互動:如何讓多個 Fragment 之間互相溝通!
明天見!